package com.api.gbhg.liuwenbo.api;

import com.alibaba.fastjson.JSON;
import com.api.gbhg.liuwenbo.action.AmountVerification;
import com.api.gbhg.liuwenbo.dao.BudgetSectionItemListDao;
import com.api.gbhg.liuwenbo.dao.DataBaseUtil;
import com.api.gbhg.liuwenbo.dao.NonCentralTreeDBUtil;
import com.api.gbhg.liuwenbo.pojo.BudgetSection;
import com.api.gbhg.liuwenbo.pojo.BudgetSectionSubtotal;
import com.api.gbhg.liwenjun.VersionFlowUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import weaver.conn.RecordSet;
import weaver.file.Prop;
import weaver.general.BaseBean;
import weaver.general.Util;

import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description 预算科支出项目预算列表
 * @Author lwb
 * @Date 2021.11.17
 */
@Path("gb/BudgetSection")
public class BudgetSectionItemListApi {

    private static final Logger logger = LoggerFactory.getLogger("gbhg");

    //预算编制各流程Workflowid
    //BZ01 海关离退休人员工资津贴补贴经费新增表
    private String BZ01Workflowid ;
    //BZ02 通用项目新增表
    private String BZ02Workflowid ;
    //BZ03 物业管理费用新增表
    private String BZ03Workflowid ;
    //BZ04 办公用品定额包干经费需求表
    private String BZ04Workflowid ;
    //BZ05 拱北海关报刊订阅审批表
    private String BZ05Workflowid ;
    //BZ06 拱北海关报刊订阅审批表（年度增订）
    private String BZ06Workflowid ;
    //BZ07 不占编合同工劳务费需求表
    private String BZ07Workflowid ;
    //BZ08 复印纸、打印纸用量需求表
    private String BZ08Workflowid ;
    //BZ09 公共图书馆、阅览室订阅审批表
    private String BZ09Workflowid ;
    //BZ10 教育培训经费
    private String BZ10Workflowid ;
    //BZ11 海关在职行政人员工资津补贴经费需求表
    private String BZ11Workflowid ;
    //BZ12 警察在职行政人员工资津贴补贴经费需求表
    private String BZ12Workflowid ;
    //BZ13 事业单位离退休人员工资津贴补贴经费需求表
    private String BZ13Workflowid ;
    //BZ14 事业单位在职人员工资津贴补贴经费需求表
    private String BZ14Workflowid ;
    //BZ15 海关养老保险缴费经费需求表
    private String BZ15Workflowid ;
    //BZ16 海关医疗保险缴费经费需求表
    private String BZ16Workflowid ;
    //BZ17 住房改革支出经费需求表
    private String BZ17Workflowid ;
    //BZ18 总署下发项目导入
    private String BZ18Workflowid ;

    private Map<String,Object> msgMap ;

    List<String> workflowIdList = new ArrayList<>();

    private static Map<String, Object> Srysfl;

    private BudgetSectionItemListDao budDao = new BudgetSectionItemListDao();

    static {
        Srysfl = new HashMap<>();
        RecordSet rs = new RecordSet();
        String sql = "select id,mc from uf_srysfl";
        rs.executeQuery(sql);
        while (rs.next()){
            Srysfl.put(rs.getString("id"),rs.getString("mc"));
        }
    }

    /**
     * 加载表单id配置文件
     */
    public void loadWorkflowId(){
        BZ01Workflowid = Prop.getPropValue("FormationWorkflowid","BZ01Workflowid");
        BZ02Workflowid = Prop.getPropValue("FormationWorkflowid","BZ02Workflowid");
        BZ03Workflowid = Prop.getPropValue("FormationWorkflowid","BZ03Workflowid");
        BZ04Workflowid = Prop.getPropValue("FormationWorkflowid","BZ04Workflowid");
        BZ05Workflowid = Prop.getPropValue("FormationWorkflowid","BZ05Workflowid");
        BZ06Workflowid = Prop.getPropValue("FormationWorkflowid","BZ06Workflowid");
        BZ07Workflowid = Prop.getPropValue("FormationWorkflowid","BZ07Workflowid");
        BZ08Workflowid = Prop.getPropValue("FormationWorkflowid","BZ08Workflowid");
        BZ09Workflowid = Prop.getPropValue("FormationWorkflowid","BZ09Workflowid");
        BZ10Workflowid = Prop.getPropValue("FormationWorkflowid","BZ10Workflowid");
        BZ11Workflowid = Prop.getPropValue("FormationWorkflowid","BZ11Workflowid");
        BZ12Workflowid = Prop.getPropValue("FormationWorkflowid","BZ12Workflowid");
        BZ13Workflowid = Prop.getPropValue("FormationWorkflowid","BZ13Workflowid");
        BZ14Workflowid = Prop.getPropValue("FormationWorkflowid","BZ14Workflowid");
        BZ15Workflowid = Prop.getPropValue("FormationWorkflowid","BZ15Workflowid");
        BZ16Workflowid = Prop.getPropValue("FormationWorkflowid","BZ16Workflowid");
        BZ17Workflowid = Prop.getPropValue("FormationWorkflowid","BZ17Workflowid");
        BZ18Workflowid = Prop.getPropValue("FormationWorkflowid","BZ18Workflowid");

        workflowIdList.add(BZ01Workflowid);
        workflowIdList.add(BZ02Workflowid);
        workflowIdList.add(BZ03Workflowid);
        workflowIdList.add(BZ04Workflowid);
        workflowIdList.add(BZ05Workflowid);
        workflowIdList.add(BZ06Workflowid);
        workflowIdList.add(BZ07Workflowid);
        workflowIdList.add(BZ08Workflowid);
        workflowIdList.add(BZ09Workflowid);
        workflowIdList.add(BZ10Workflowid);
        workflowIdList.add(BZ11Workflowid);
        workflowIdList.add(BZ12Workflowid);
        workflowIdList.add(BZ13Workflowid);
        workflowIdList.add(BZ14Workflowid);
        workflowIdList.add(BZ15Workflowid);
        workflowIdList.add(BZ16Workflowid);
        workflowIdList.add(BZ17Workflowid);
        workflowIdList.add(BZ18Workflowid);

        msgMap = new HashMap<>();
    }

    @POST
    @Path("/getProjectList")
    @Produces(MediaType.APPLICATION_JSON)
    public String getProjectList(Map<String,Object> param){
        logger.info("进入getProjectList方法---------------：");
        this.loadWorkflowId();

        if (!param.containsKey("nf") || !param.containsKey("sbdw")){
            msgMap.put("code","500");
            msgMap.put("msg","缺少参数 请检查参数是否完整！");
            msgMap.put("data","");
            return JSON.toJSONString(msgMap);
        }

        List<BudgetSectionSubtotal> data = null;
        try {
            List<BudgetSection> list = getSectionsData(param);
            data = setSortAndSubtotal(list);
        } catch (Exception e) {
            logger.info("异常---------------："+e.toString());
            msgMap.put("code","500");
            msgMap.put("msg","程序异常！请联系管理员");
            msgMap.put("data","");
            e.printStackTrace();
            return JSON.toJSONString(msgMap);
        }
        msgMap.put("code","200");
        msgMap.put("msg","");
        msgMap.put("data",data);

        return JSON.toJSONString(msgMap);
    }


    public List<BudgetSection> getSectionsData(Map<String,Object> param)throws Exception{
        List<BudgetSectionSubtotal> listTotal = new ArrayList<>();
        List<BudgetSection> list = new ArrayList<>();
        RecordSet rs = new RecordSet();
        RecordSet rs2 = new RecordSet();
        BaseBean baseBean = new BaseBean();
        String YJ = baseBean.getPropValue("Verification","yj");
        String XJ = baseBean.getPropValue("Verification","xj");
        for (String wid:workflowIdList) {

            //表单名称
            String tableName = DataBaseUtil.getWorkflowTabNameByWid(wid);
            int formid = VersionFlowUtil.getFlowTableLableId(wid);
            //当年预算以及上年预算明细表名
            List<String> detailTables = AmountVerification.getDetailTables(formid);
            String sql = "";
            if (!wid.equals(BZ18Workflowid)){
                //根据参数选定sql
                if (param.get("nf").equals("")&&!param.get("sbdw").equals("")){
                    sql = "select requestid,id,ysnd,xmmc,sbdw,szdlhsdw from "+tableName+" where ysnd = "+ LocalDate.now().getYear()+" and sbdw = "+param.get("sbdw")+"  ";
                }else if(!param.get("nf").equals("")&&param.get("sbdw").equals("")){
                    sql = "select requestid,id,ysnd,xmmc,sbdw,szdlhsdw from "+tableName+" where ysnd = "+ param.get("nf")+"  ";
                }else if(!param.get("nf").equals("")&&!param.get("sbdw").equals("")){
                    sql = "select requestid,id,ysnd,xmmc,sbdw,szdlhsdw from "+tableName+" where ysnd = "+ param.get("nf")+"  "+" and sbdw = "+param.get("sbdw")+"  ";
                }else{
                    sql = "select requestid,id,ysnd,xmmc,sbdw,szdlhsdw from "+tableName+" where ysnd = "+ LocalDate.now().getYear()+"  ";
                }
            }else {
                if (param.get("nf").equals("")&&!param.get("sbdw").equals("")){
                    sql = "select requestid,id,ysnd,sheet1_main_field5 as xmmc,sbdw,szdlhsdw from "+tableName+" where ysnd = "+ LocalDate.now().getYear()+" and sbdw = "+param.get("sbdw")+"  ";
                }else if(!param.get("nf").equals("")&&param.get("sbdw").equals("")){
                    sql = "select requestid,id,ysnd,sheet1_main_field5 as xmmc,sbdw,szdlhsdw from "+tableName+" where ysnd = "+ param.get("nf")+"  ";
                }else if(!param.get("nf").equals("")&&!param.get("sbdw").equals("")){
                    sql = "select requestid,id,ysnd,sheet1_main_field5 as xmmc,sbdw,szdlhsdw from "+tableName+" where ysnd = "+ param.get("nf")+"  "+" and sbdw = "+param.get("sbdw")+"  ";
                }else{
                    sql = "select requestid,id,ysnd,sheet1_main_field5 as xmmc,sbdw,szdlhsdw from "+tableName+" where ysnd = "+ LocalDate.now().getYear()+"  ";
                }
            }
            rs.executeQuery(sql);
            while (rs.next()) {

                boolean isRequestid = budDao.IsJinfeiVersion(rs.getString("requestid"));
                if (!isRequestid)
                    continue;//次跳数据如果在经费表不存在则跳过

                BudgetSection bs = new BudgetSection();
                //主表id
                String id = rs.getString("id");
                bs.setId(id);
                //申报单位id
                String sbdwid = Util.null2String(rs.getString("sbdw"));
                if (sbdwid.equals(""))
                    continue;
                bs.setSbdwid(sbdwid);
                bs.setSbdw(DataBaseUtil.getSubcompanyNameById(sbdwid));
                //独立核算单位
                String szdlhsdw = Util.null2String(rs.getString("szdlhsdw"));
                bs.setSzdlhsdwid(szdlhsdw);
                bs.setSzdlhsdw(DataBaseUtil.getSubcompanyNameById(szdlhsdw));
                bs.setJdid(DataBaseUtil.getNodeid(rs.getString("requestid"))+"");
                bs.setJdmc(DataBaseUtil.getNodeName(rs.getString("requestid"))+"");//节点名称
                //bs.setXmmc(rs.getString("xmmc"));
                bs.setXmmc(budDao.getJingFeiXmmc(rs.getString("requestid")));


                //开始给核批渠道赋值
                int i=0;
                Map<String,Object> map = new HashMap<>();
                for (String dtab : detailTables) {
                    String ysField = "dfczbkxmdnys";
                    if (i==1)
                        ysField = "dfczbkxmsnjz";

                    String dSql = "select * from " + dtab + " where mainid = " + id + " ";
                    rs2.executeQuery(dSql);
                    //System.err.println(dSql);
                    while (rs2.next()) {
                        if (rs2.getString("srlx").equals("0")) { //0为中央 中央（科目 科目下级组成）
                            String[] zyczbksr = rs2.getString("zyczbksr").split("_");
                            if (zyczbksr[0].equals(YJ)){
                                String kmdm = budDao.getKmdm(zyczbksr[1]);
                                if (i==1)
                                    kmdm = "上年结转-"+kmdm;
                                map.put(kmdm,rs2.getString("hpje"));
                            }else{
                                String zyhpqd = budDao.getKmdmByXjId(zyczbksr[1])+">"+budDao.getzyhpqd(zyczbksr[1]);
                                if (i==1)
                                    zyhpqd = "上年结转-"+zyhpqd;
                                map.put(zyhpqd,rs2.getString("hpje"));
                            }
                        } else {
                            String zcqd = rs2.getString("zcqd");
                            String xmhpqd = zcqd.equals("8") || zcqd.equals("5") ?
                                    Srysfl.get(zcqd).toString()+">"+ NonCentralTreeDBUtil.getCustomFieldsByXmid(rs2.getString(ysField),"xmmc") :
                                    Srysfl.get(zcqd).toString();
                            if (i==1)
                                xmhpqd = "上年结转-"+xmhpqd;
                            map.put(xmhpqd,rs2.getString("hpje"));
                        }
                    }
                    i++;
                }
                //如果没有核批渠道数据 那么就不需要记录次条数据
                if (map.size() == 0){
                    continue;
                }
                bs.setXmhpqd(map);
                //----------------
                //取总额
                String dtXhHj = budDao.getDetailTableXhHj(formid,id);
                bs.setZe(dtXhHj);

                //取政府购买服务值
//                List<String> detailTables1 = budDao.getDetailTables1(formid);
//                String dtsumsql = budDao.joinDtSumSql(detailTables1,id);
//                rs2.executeQuery(dtsumsql);
//                rs2.next();
//                bs.setZfgmfw(Util.null2String(rs2.getString("yjjewy")));

                //字段存在问题 暂时取0
                if(wid.equals(BZ01Workflowid)||wid.equals(BZ11Workflowid)||wid.equals(BZ12Workflowid)||wid.equals(BZ13Workflowid)||wid.equals(BZ14Workflowid)
                        ||wid.equals(BZ15Workflowid)||wid.equals(BZ16Workflowid)||wid.equals(BZ17Workflowid)||wid.equals(BZ18Workflowid)){
                    //政府购买服务
                    bs.setZfgmfw("0");
                    //取值 政府采购
                    bs.setHwgz("0");
                    bs.setGc("0");
                    bs.setFw("0");
                    bs.setXecg("0");
                }else {
                    //取值 政府购买服务/政府采购
                    Map<String,Object> dtZfGmZe = budDao.getDetailTableZfGmZe(formid,id);
                    bs.setZfgmfw(String.valueOf(dtZfGmZe.get("zfcgfwy")));
                    bs.setHwgz(String.valueOf(dtZfGmZe.get("hwgz")));
                    bs.setGc(String.valueOf(dtZfGmZe.get("gc")));
                    bs.setFw(String.valueOf(dtZfGmZe.get("fw")));
                    bs.setXecg(String.valueOf(dtZfGmZe.get("xecg")));
                }

                list.add(bs);
            }

        }
        System.err.println(list.size());
        return list;
    }

    /**
     * 设置排序以及计算小计
     * @param paramList
     * @return
     * @throws Exception
     */
    public List<BudgetSectionSubtotal> setSortAndSubtotal(List<BudgetSection> paramList)throws Exception{
        List<BudgetSectionSubtotal> list = new ArrayList<>();
        for (BudgetSection v:paramList) {
            int i = 0;
            for (BudgetSectionSubtotal st:list) {

                if (st.getSbdwid().equals(v.getSbdwid())){
                    i = 1;
                    st.getList().add(v);
                    st.setZeTotal(st.getZeTotal().add(new BigDecimal(v.getZe())));
                    st.setGzTotla(st.getGzTotla().add(new BigDecimal(v.getHwgz())));
                    st.setGcTotla(st.getGcTotla().add(new BigDecimal(v.getGc())));
                    st.setFwTotla(st.getFwTotla().add(new BigDecimal(v.getFw())));
                    st.setCgTotla(st.getCgTotla().add(new BigDecimal(v.getXecg())));

                    for (Map.Entry<String,Object> entry:v.getXmhpqd().entrySet()) {
                        String s = entry.getValue().toString();
                        st.setHpqdjeTotla(st.getHpqdjeTotla().add(new BigDecimal(s)));
                    }

                    st.setZfgmTotla(st.getZfgmTotla().add(new BigDecimal(v.getZfgmfw())));
                }
            }
            if (i == 0){
                BudgetSectionSubtotal subtotal = new BudgetSectionSubtotal();
                ArrayList<BudgetSection> tempList = new ArrayList<>();
                tempList.add(v);
                subtotal.setList(tempList);
                subtotal.setZeTotal(new BigDecimal(v.getZe()));
                subtotal.setGzTotla(new BigDecimal(v.getHwgz()));
                subtotal.setGcTotla(new BigDecimal(v.getGc()));
                subtotal.setFwTotla(new BigDecimal(v.getFw()));
                subtotal.setCgTotla(new BigDecimal(v.getXecg()));
                subtotal.setSbdwid(v.getSbdwid());
                subtotal.setZfgmTotla(new BigDecimal(v.getZfgmfw()));

                subtotal.setHpqdjeTotla(new BigDecimal("0"));
                for (Map.Entry<String,Object> entry:v.getXmhpqd().entrySet()) {
                    String s = entry.getValue().toString();
                    subtotal.setHpqdjeTotla(subtotal.getHpqdjeTotla().add(new BigDecimal(s)));
                }

                list.add(subtotal);
            }
        }
        return list;
    }


    public String joinCgSql(List<String> list,String mainid){
        return "select sum(je) je,lx from "+list.get(0)+" where mainid = "+mainid+" group by lx ";
    }


}
